#include "cipher.h"
#include <openssl/des.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <QDebug>

#define KEY_SIZE_16B            16
#define KEY_SIZE_24B            24
#define KEY_SIZE_32B            32

#define DES_BLOCK_SIZE 8

CCipher::CCipher(QObject *parent) : QObject(parent)
{

}


bool CCipher::encryption(const QByteArray& in, QByteArray& out, const QByteArray& key, const QByteArray& ivec, const EVP_CIPHER *cipher, bool enc)
{
    if (enc)
    {
        // 指定加密算法及key和iv
        int ret = EVP_EncryptInit_ex(ctx, cipher, NULL, (const unsigned char*)key.data(), (const unsigned char*)ivec.data());
        if(ret != 1)
        {
            return false;
        }

        // 进行加密操作
        int mlen = 0;
        out.resize(in.size() + AES_BLOCK_SIZE);
        ret = EVP_EncryptUpdate(ctx, (unsigned char*)out.data(), &mlen, (const unsigned char*)in.data(), in.size());
        if(ret != 1)
        {
            return false;
        }

        // 结束加密操作
        int flen = 0;
        ret = EVP_EncryptFinal_ex(ctx, (unsigned char *)out.data() + mlen, &flen);
        if(ret != 1)
        {
            return false;
        }
        out.resize(mlen + flen);
        return true;
    }
    else
    {
        // 指定解密算法及key和iv
        int ret = EVP_DecryptInit_ex(ctx, cipher, NULL, (const unsigned char*)key.data(), (const unsigned char*)ivec.data());
        if(ret != 1)
        {
            return false;
        }

        // 进行解密操作
        int mlen = 0;
        out.resize(in.size());
        ret = EVP_DecryptUpdate(ctx, (unsigned char*)out.data(), &mlen, (const unsigned char*)in.data(), in.size());
        if(ret != 1)
        {
            return false;
        }

        // 结束解密操作
        int flen = 0;
        ret = EVP_DecryptFinal_ex(ctx, (unsigned char *)out.data() + mlen, &flen);
        if(ret != 1)
        {
            return false;
        }
        out.resize(mlen + flen);
        return true;
    }
}


